package com.yan_jiu_sheng.LeetCodeHot100.AC;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * https://leetcode.cn/problems/letter-combinations-of-a-phone-number/description/?envType=study-plan-v2&envId=top-100-liked
 * 回溯+哈希表成功通过
 *
 * @author yulongTian
 * @create 2024-07-01 14:02
 */
public class Test57 {
    public static void main(String[] args) {
        System.out.println(new Test57().letterCombinations("234"));
    }

    public List<String> letterCombinations(String digits) {
        String[] digitStrings = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
        List<String> res = new ArrayList<>();
        if (digits.length() == 0) {
            return new ArrayList<>();
        }
//        if (digits.length() == 1) {
//            String digitString = digitStrings[digits.charAt(0) - '0'];
//            for (int i = 0; i < digitString.length(); i++) {
//                res.add("" + digitString.charAt(i));
//            }
//            return res;
//        }
        HashMap<Integer, String[]> map = new HashMap<>();
        for (int i = 2; i <= 9; i++) {
            String[] temp = new String[digitStrings[i].length()];
            for (int j = 0; j < digitStrings[i].length(); j++) {
                temp[j] = "" + digitStrings[i].charAt(j);
            }
            map.put(i, temp);
        }
        dfs(0, map, res, digits, new StringBuffer());

        return res;
    }

    public void dfs(int digitIndex, HashMap<Integer, String[]> map, List<String> res,
                    String digits, StringBuffer tempRes) {
        if (tempRes.length() == digits.length()) {
            res.add(tempRes.toString());
            return;
        }
        //选择第i组中的第j个
        for (int i = digitIndex; i < digits.length(); i++) {
            String[] strings = map.get(digits.charAt(i) - '0');
            for (int j = 0; j < strings.length; j++) {
                tempRes.append(strings[j]);
                dfs(i + 1, map, res, digits, tempRes);
                tempRes.deleteCharAt(tempRes.length() - 1);
            }
        }
    }

}
